{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "48cbf121",
   "metadata": {},
   "outputs": [],
   "source": [
    "# -*- coding: utf-8 -*-\n",
    "import pandas as pd\n",
    "import numpy as np\n",
    "import matplotlib.pyplot as plt\n",
    "from matplotlib.font_manager import FontProperties\n",
    "\n",
    "# 设置中文显示\n",
    "plt.rcParams['font.sans-serif'] = ['SimHei']  # Windows系统\n",
    "# plt.rcParams['font.sans-serif'] = ['Arial Unicode MS']  # Mac系统\n",
    "plt.rcParams['axes.unicode_minus'] = False\n",
    "\n",
    "##加载数据（替换为实际文件路径）\n",
    "file_path = \"D:\\\\BaiduNetdiskDownload\\\\微博评论_202505061835.csv\"  # 修改后的文件路径\n",
    "df = pd.read_csv(file_path, parse_dates=['time'], encoding='utf-8')\n",
    "\n",
    "# 时间解析增强（处理带时区的时间格式）\n",
    "def parse_custom_time(time_str):\n",
    "    return pd.to_datetime(time_str, format='%a %b %d %H:%M:%S %z %Y')\n",
    "\n",
    "df['time'] = df['time'].apply(parse_custom_time)\n",
    "\n",
    "# 时间维度分析函数\n",
    "def time_analysis(data, time_col='time'):\n",
    "    # 复制数据防止修改原数据\n",
    "    df = data.copy()\n",
    "\n",
    "    # 1. 按小时统计评论量\n",
    "    df['hour'] = df[time_col].dt.hour\n",
    "    hourly_counts = df.groupby('hour').size().reset_index(name='counts')\n",
    "\n",
    "    # 2. 按分钟计算滑动窗口（15分钟窗口，5分钟步长）\n",
    "    df['minute'] = df[time_col].dt.floor('5min')  # 5分钟精度\n",
    "    window_size = '15min'  # 滑动窗口大小\n",
    "    rolling_counts = df.set_index('minute').resample('5min').size()  # 5分钟粒度\n",
    "    rolling_counts = rolling_counts.rolling(window_size, min_periods=1).sum().reset_index(name='rolling_count')\n",
    "\n",
    "    # 3. 突发增长检测（Z-score方法）\n",
    "    rolling_mean = rolling_counts['rolling_count'].mean()\n",
    "    rolling_std = rolling_counts['rolling_count'].std()\n",
    "    rolling_counts['z_score'] = (rolling_counts['rolling_count'] - rolling_mean) / rolling_std\n",
    "    bursts = rolling_counts[rolling_counts['z_score'] > 2]  # 超过2个标准差视为突发\n",
    "\n",
    "    return hourly_counts, rolling_counts, bursts\n",
    "\n",
    "# 执行分析\n",
    "hourly_data, rolling_data, burst_points = time_analysis(df)\n",
    "\n",
    "# 可视化设置\n",
    "fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(12, 10))\n",
    "\n",
    "# 1. 小时分布柱状图\n",
    "colors = ['#4B8BBE' if h not in [12, 16] else '#FF6B6B' for h in hourly_data['hour']]\n",
    "ax1.bar(hourly_data['hour'], hourly_data['counts'], color=colors)\n",
    "ax1.set_title('评论量小时分布', fontsize=14, pad=20)\n",
    "ax1.set_xlabel('时段（小时）', fontsize=12)\n",
    "ax1.set_ylabel('评论数量', fontsize=12)\n",
    "ax1.grid(axis='y', linestyle='--', alpha=0.7)\n",
    "\n",
    "# 标注特殊时段\n",
    "ax1.annotate('活动启动期', xy=(12, hourly_data.loc[hourly_data['hour']==12, 'counts'].values[0]),\n",
    "             xytext=(10, -30), textcoords='offset points',\n",
    "             arrowprops=dict(arrowstyle=\"->\", connectionstyle=\"arc3\"))\n",
    "ax1.annotate('答案公布期', xy=(16, hourly_data.loc[hourly_data['hour']==16, 'counts'].values[0]),\n",
    "             xytext=(16, -30), textcoords='offset points',\n",
    "             arrowprops=dict(arrowstyle=\"->\", connectionstyle=\"arc3\"))\n",
    "\n",
    "# 2. 滑动窗口趋势图\n",
    "ax2.plot(rolling_data['minute'], rolling_data['rolling_count'],\n",
    "        color='#2E86C1', linewidth=2, label='评论量')\n",
    "ax2.scatter(burst_points['minute'], burst_points['rolling_count'],\n",
    "           color='#E74C3C', zorder=5, label='突发时段')\n",
    "\n",
    "# 标注突发点\n",
    "for idx, row in burst_points.iterrows():\n",
    "    ax2.annotate(f\"峰值: {row['rolling_count']}\",\n",
    "                xy=(row['minute'], row['rolling_count']),\n",
    "                xytext=(0, 10), textcoords='offset points',\n",
    "                ha='center', color='#E74C3C')\n",
    "\n",
    "ax2.set_title('15分钟滑动窗口评论趋势', fontsize=14, pad=20)\n",
    "ax2.set_xlabel('时间', fontsize=12)\n",
    "ax2.set_ylabel('评论数量', fontsize=12)\n",
    "ax2.legend()\n",
    "ax2.grid(linestyle='--', alpha=0.7)\n",
    "\n",
    "# 优化时间轴显示\n",
    "ax2.xaxis.set_major_formatter(plt.matplotlib.dates.DateFormatter('%H:%M'))\n",
    "plt.setp(ax2.get_xticklabels(), rotation=45, ha='right')\n",
    "\n",
    "plt.tight_layout()\n",
    "plt.show()\n",
    "\n",
    "# 输出分析结果\n",
    "print(\"\\n【分析结果】\")\n",
    "print(f\"1. 高峰时段：{hourly_data.loc[hourly_data['counts'].idxmax(), 'hour']}时\")\n",
    "print(f\"2. 突发次数：{len(burst_points)}次\")\n",
    "print(\"3. 突发时间点：\")\n",
    "print(burst_points[['minute', 'rolling_count']].to_string(index=False))\n"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "pytorch",
   "language": "python",
   "name": "env_name"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.9.21"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
